package com.example.musicdemo.base

import android.graphics.Color
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.musicdemo.R
import kotlinx.android.synthetic.main.fragment_home.*


/**
 * ClassName:BaseListFragment
 * Description:所有具有下拉刷新和上拉加载更多列表界面的基类
 * 基类抽取
 * HomeView->BaseView
 * Presenter->BaseListPresenter
 * Adapter->BaseListAdapter
 */
abstract class BaseListFragment<RESPONSE, ITEM_BEAN, ITEM_VIEW : View> : BaseFragment(),
    BaseView<RESPONSE> {

    private val adapter by lazy { getSpecialAdapter() }
    val presenter by lazy { getSpecialPresenter() }
    abstract fun getSpecialPresenter(): BaseListPresenter


    override fun onError(message: String?) {
        refreshLayout?.isRefreshing = false
        myToast("加载数据失败")
    }


    /**
     * 成功加载刷新的回调函数
     */
    override fun loadSuccess(reponse: RESPONSE?) {
        //隐藏刷新控件
        refreshLayout?.isRefreshing = false
        //刷新列表
        adapter.updateList(getList(reponse))
    }


    /**
     * 成功加载更多的函数
     */
    override fun loadMore(response: RESPONSE?) {
        adapter.loadMore(getList(response))
    }


    override fun initView(): View? {

        return View.inflate(context, R.layout.fragment_home, null)

    }


    override fun initListener() {
        recycleView.layoutManager = LinearLayoutManager(context)
        recycleView.adapter = adapter
        //初始化刷新控件
        refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.GREEN)
        //刷新监听
        refreshLayout.setOnRefreshListener {

            presenter.loadData()
        }

        recycleView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {

                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //看看是否是最后一条
                    val layoutManager = recyclerView.layoutManager
                    if (layoutManager is LinearLayoutManager) {
                        val manager: LinearLayoutManager = layoutManager
                        val lastPosition = manager.findLastVisibleItemPosition()
                        if (lastPosition == adapter.itemCount - 1) {
                            //加载更多
                            presenter.loadMore(adapter.itemCount - 1)
                        }
                    }

                }
            }
        })

    }

    override fun initData() {
        //初始化数据
        presenter.loadData()
    }

    abstract fun getList(response: RESPONSE?): List<ITEM_BEAN>?


    /**
     * 获取适配器adapter
     */
    abstract fun getSpecialAdapter(): BaseListAdapter<ITEM_BEAN, ITEM_VIEW>
}